import os
import sys

from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (QApplication, QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QTextBrowser,
                             QMessageBox, QFileDialog)
from PyQt5.QtCore import *

import json
import cv2
import base64
import requests


class MyOCR(QThread):
    text_list = pyqtSignal(list)

    def __init__(self,path):
        super(MyOCR, self).__init__()
        self.path = path

    def run(self):
        res = self.start_ocr(self.path)
        self.text_list.emit(res)


    def cv2_to_base64(self, image):
        data = cv2.imencode('.jpg', image)[1]
        return base64.b64encode(data.tobytes()).decode('utf8')

    def start_ocr(self, path):
        # 发送HTTP请求
        data = {'images': [self.cv2_to_base64(cv2.imread(path))]}
        headers = {"Content-type": "application/json"}
        #url = "http://192.168.1.64:8866/predict/chinese_ocr_db_crnn_mobile"
        url = "http://192.168.1.64:8866/predict/ocr_system"
        r = requests.post(url=url, headers=headers, data=json.dumps(data))

        # 打印预测结果
        print(r.json()["results"])
        res = []
        for m_json in r.json()["results"][0]:
            print(m_json['text'])
            res.append(m_json['text'])
        return res



class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.resize(800,400)
        self.setContentsMargins(30,10,30,30)
        self.path = ''

        #创建读取图片按钮，OCR按钮
        self.imagePasteButton = QPushButton("读取剪切板图片")
        self.imagePasteButton.setMinimumHeight(50)
        self.fileButton = QPushButton("打开一个文件")
        self.fileButton.setMinimumHeight(50)
        self.OCRButton = QPushButton('OCR识别')
        self.OCRButton.setMinimumHeight(50)


        #创建文本标签和图像标签，显示文本和图像
        self.imageLabel = QLabel()
        self.imageLabel.setMaximumWidth(400)
        self.imageLabel.setMaximumHeight(300)
        self.brose = QTextBrowser()
        self.brose.setMaximumWidth(400)
        self.brose.setMinimumWidth(400)

        #设置布局
        layout = QVBoxLayout()
        layout.setSpacing(20)
        button_layout = QHBoxLayout()
        button_layout.setSpacing(50)

        image_layout = QHBoxLayout()
        button_layout.addWidget(self.imagePasteButton)
        button_layout.addWidget(self.fileButton)
        button_layout.addWidget(self.OCRButton)

        image_layout.addWidget(self.imageLabel)
        image_layout.addWidget(self.brose)
        layout.addLayout(button_layout)
        layout.addLayout(image_layout)

        #设置主窗口的布局，自定义槽函数，设置标题
        self.setLayout(layout)
        self.imagePasteButton.clicked.connect(self.pasteImage)
        self.fileButton.clicked.connect(self.open_file)
        self.OCRButton.clicked.connect(self.translate)
        self.setWindowTitle("OCR识别服务（基于paddle--作者：罗赛）")

    def pasteImage(self):
        #实例化剪切板，z设置图像标签的图片加载，从剪切板获取路径
        clipboard = QApplication.clipboard()
        if clipboard.pixmap().isNull() is True:
            QMessageBox.about(self, "错误", "未读取到图片!")
        else:
            self.imageLabel.setPixmap(clipboard.pixmap())
            clipboard.pixmap().save('./temp.jpg')
            self.path = r"./temp.jpg"
            #print (self.cv2_to_base64(clipboard.pixmap()))

    def translate(self):
        self.OCRButton.setDisabled(True)
        self.OCRButton.setText('正在识别中...')
        self.brose.clear()
        if self.path == '':
            QMessageBox.warning(self, "错误", "未读取到图片!")
        else:
            print('正在识别')
            self.brose.append('正在识别中...')
            self.brose.append('--------------')
            self.ocr = MyOCR(self.path)
            self.ocr.text_list.connect(self.show_brose)
            self.ocr.start()

    def show_brose(self,res):
        self.OCRButton.setText('OCR识别')
        self.OCRButton.setDisabled(False)

        for text in res:
            self.brose.append(text)

    def open_file(self):
        # 单文件，暂不使用
        # path, _ = QFileDialog.getOpenFileName(self, "打开文件", "", "Excel文件 (*.xls);Excel文件 (*.xlsx);所有文件 (*.*)")
       # path, format = QFileDialog.getOpenFileName(self, "选择一个文件", ".", filter="图片 (*.jpg);;位图 (*.png)")
        path, format = QFileDialog.getOpenFileName(self, "选择一个文件", ".", filter="图片 (*.jpg)")

        if path:
            self.brose.clear()
            text = '您添加的文件为：\n' + str(os.path.basename(path))
            # filelist = os.listdir(path)
            self.brose.append(text)
            self.brose.append('--------------')
            self.path = path
            self.imageLabel.setPixmap(QPixmap(self.path))


if __name__ == "__main__":
    if hasattr(Qt, 'AA_EnableHighDpiScaling'):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
        QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
    from qt_material import apply_stylesheet # 第三方style

    app = QApplication(sys.argv)
    form = Form()
    # setup stylesheet
    '''
    1、light_blue.xml
    2、dark_teal.xml
    '''
    apply_stylesheet(form, theme='dark_teal.xml')
    form.show()
    sys.exit(app.exec_())


